package cn.wit.summit.chwan.tools.downloadtool;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.models.dto.ResponseEnergyNumber;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.response.IndexBeanV3Response;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.ui.receiver.BroadcastAction;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.Constants;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.MobileCodeUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PermissionManagerUtil;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.MessageDialog;
import retrofit2.Retrofit;

/**
 * Created by pengsk on 2018/4/11.
 */

public class DownloadTool {
    public static void stopTask(DownLoadTaskTable downLoadTask) {
        DownloadTaskManager.getInstance().updateStatusBygameId(downLoadTask.getGameId(), DownLoadStatusConfig.DOWNLOAD_STOP);
        DownloadFactory.get().stopTask(downLoadTask.getGameId());
    }

    public static void deletTask(DownLoadTaskTable downLoadTask) {
        if (downLoadTask==null) return;
        DownloadFactory.get().deletTask(downLoadTask.getGameId());
        DownloadTaskManager.getInstance().deleteTaskTable(downLoadTask.getGameId());
        String path = downLoadTask.getDownPath();
        if (StringUtils.isNotEmpty(path) && new File(path).exists()) {
            UtilsMy.delete(new File(path));
        }
        if (downLoadTask.getGameType() == 1 && downLoadTask.getDownStatus() != DownLoadStatusConfig.DOWNLOADING && downLoadTask.getDownStatus() != DownLoadStatusConfig.WAIT) {
            String obbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/obb/" + downLoadTask.getPackageName();
            File file = new File(obbPath);
            if (file.exists()) {
                UtilsMy.delete(file);
            }
        }
        if (downLoadTask.getGameType() == 2 && downLoadTask.getDownStatus() != DownLoadStatusConfig.DOWNLOADING && downLoadTask.getDownStatus() != DownLoadStatusConfig.WAIT) {
            String obbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + downLoadTask.getPackageName();
            File file = new File(obbPath);
            if (file.exists()) {
                UtilsMy.delete(file);
            }
        }
        downLoadTask.setDownStatus(DownLoadStatusConfig.DELETED);
        EventBus.getDefault().post(downLoadTask.getDownEvent());
    }

    public static void unzip(Context context, DownLoadTaskTable downloadTask) {
        DownloadTaskManager.getInstance().updateStatusBygameId(downloadTask.getGameId(), DownLoadStatusConfig.UNZIP);
        DownloadFactory.get().upZipThread(context, downloadTask);
    }

    public static void downloadGame(final Context context, final DownLoadTaskTable downLoadTask, IndexBeanV3Response.CreditInfoBean info, boolean isDetial) {
        if (StringUtils.isEmpty(downLoadTask.getGameId())) {
            ToastUtils.getInstance(context).showToastSystem("游戏数据出错，下载失败！");
            return;
        }
        if (NetWorkUtils.isNetworkConnected(context)) {
            if (NetWorkUtils.isWifiConnected(context)) {
                startDownRealy(context, downLoadTask, isDetial, info);
            } else {
                Intent intent = new Intent("com.send.message.showNotWifitodown");
                intent.putExtra("showNotWifitodownTask", downLoadTask);
                context.sendBroadcast(intent);
            }

        } else {
            addTaskToDB(context, downLoadTask, isDetial, info);
            ToastUtils.getInstance(context).showToastSystem("请检查网络是否已连接");
        }
    }

    public static void downloadGame(final Context context, final DownLoadTaskTable downLoadTask, IndexBeanV3Response.CreditInfoBean info) {
        downloadGame(context, downLoadTask, info, false);
    }

    private static long getSDFreeSize() {
        try {
            //取得SD卡文件路径
            File path = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(path.getPath());
            //获取单个数据块的大小(Byte)
            long blockSize = sf.getBlockSize();
            //空闲的数据块的数量
            long freeBlocks = sf.getAvailableBlocks();
            //返回SD卡空闲大小
            return freeBlocks * blockSize;  //单位Byte
//        return (freeBlocks * blockSize)/1024;   //单位KB
//        return (freeBlocks * blockSize)/1024 /1024; //单位MB
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void sendMessageEnergy(final Context context, final String gameID) {
        try {
            int uid = AccountUtil.getInstance().getUid();
            if (uid != 0) {

                RetrofitManager retrofitManager = RetrofitManager.getInstance(context);
                Retrofit retrofit = retrofitManager.getEnergyRetrofit();
                ApiUtil apiUtil = retrofit.create(ApiUtil.class);
                apiUtil.downEnnerGhy(uid, AccountUtil.getInstance().getToken(), gameID, "NewGame").enqueue(new MyCallback<ResponseBase<ResponseEnergyNumber>>() {
                    @Override
                    public void onSuccess(ResponseBase<ResponseEnergyNumber> model) {
                        ResponseEnergyNumber data = model.getData_info();
                        try {
                            if (gameID.equals(PreferenceUtil.getPreferences(context, "toursEnergyPreGameID")))
                                PreferenceUtil.savePreference(context, "toursEnergyPreGameID", "");
                            EnergyEvent energyEvent = new EnergyEvent();
                            if (data != null && data.getEnergies() > 0) {
                                energyEvent.setNumber(data.getEnergies());
                                EventBus.getDefault().post(energyEvent);
                                AccountBean accountBean = AccountUtil.getInstance().getAccountData();
                                if (accountBean != null) {
                                    accountBean.setEnergies(accountBean.getEnergies() + data.getEnergies());
                                    AccountUtil.getInstance().saveAccountData(accountBean);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {

                    }
                });
            } else {
                PreferenceUtil.savePreference(context, "toursEnergyPreGameID", gameID);
                EnergyEvent energyEvent = new EnergyEvent();
                energyEvent.setTours(true);
                energyEvent.setNumber(MyApplication.cfgPlug.getValue_default_energy_num());
                EventBus.getDefault().post(energyEvent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void startDownRealy(Context context, DownLoadTaskTable downLoadTask, boolean isDetial, IndexBeanV3Response.CreditInfoBean info) {

//        try {
//            EnergyEvent energyEvent = new EnergyEvent();
//            energyEvent.setNumber(100);
//            EventBus.getDefault().post(energyEvent);
//            AccountBean accountBean=AccountUtil.getInstance().getAccountData();
//            if (accountBean!=null){
//                accountBean.setEnergies(accountBean.getEnergies()+100);
//                AccountUtil.getInstance().saveAccountData(accountBean);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        long sizeAlive = getSDFreeSize();
        if (sizeAlive < downLoadTask.getTotalSize() * 3 / 2) {
            ToastUtils.getInstance(context).showToastSystem("存储空间不足");
            return;
        }
        File file = new File(Constants.PATH_DOWNLOAD);
        boolean hasPermiss = PermissionManagerUtil.hasStoragePermission(context);
        if (!hasPermiss) {
            Intent intent = new Intent(BroadcastAction.ACTION_CHECKANDREQUEST_PERMISS);
            intent.putExtra("permisson", PermissionManagerUtil.PERM_STORAGE);
            context.sendBroadcast(intent);
            return;
        }
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return;
            }
        }
        addTaskToDB(context, downLoadTask, isDetial, info);
    }

    private static void addTaskToDB(final Context context, final DownLoadTaskTable downLoadTask, final boolean isDetial, IndexBeanV3Response.CreditInfoBean info) {

        String fileName = downLoadTask.getDownloadUrl().substring(downLoadTask.getDownloadUrl().lastIndexOf("/") + 1);
        downLoadTask.setDownPath(Constants.PATH_DOWNLOAD + fileName);
        DownLoadTaskTable tableDb = DownloadTaskManager.getInstance().findByGameId(downLoadTask.getGameId());
        downLoadTask.setDownStatus(DownLoadStatusConfig.WAIT);
        if (tableDb == null) {
            if (AccountUtil.getInstance().getAccountData().getAllowCredit().equals("0") && info!=null) {
                DownloadEvent downloadEvent = new DownloadEvent(downLoadTask.getDownloadUrl()
                        , DownLoadStatusConfig.NORMAL, 0, "0", downLoadTask.getGameId());
                EventBus.getDefault().post(downloadEvent);

                final MessageDialog messageDialog = new MessageDialog(context);
                messageDialog.show();
                messageDialog.setTitle(context.getResources().getString(R.string.comment_dialog_title_str));
                messageDialog.setMsg("一起玩APP，是一个非常重视信用的平台，为了防止不必要扣除信用，请先完成一起玩的信用理解测试。");
                messageDialog.setCancelBtn("下次吧！", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        messageDialog.dismiss();
                    }
                });
                messageDialog.setOkBtn("参加信用分测试", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        messageDialog.dismiss();
                        IntentUtil.getInstance().goShareWebActivity(context, RpcConstant.forumLoginRootUrl+"/static_v3/survey.html");
                    }
                });
            } else {
                downLoadTask.setDownStartTime(System.currentTimeMillis());
                DownloadTaskManager.getInstance().insertDownload(downLoadTask);
                sendMessageEnergy(context, downLoadTask.getGameId());
                StatFactory.getInstance().sendGameDownload(context, downLoadTask.getGameId(),3+"",isDetial);
                DownloadFactory.get().addTask(new DownloadTask(downLoadTask.getDownloadUrl(), downLoadTask.getDownPath(), downLoadTask.getGameId(), downLoadTask.getTotalSize()));

                MobileCodeUtils.taskDownloadGameTag(context, downLoadTask.getGameId(), 1);
            }

//            MobileCodeUtils.checkDownloadedGame(context, downLoadTask.getGameId(), new OnIsDownloadInterface(){
//                @Override
//                public void onResult() {
//                    downLoadTask.setDownStartTime(System.currentTimeMillis());
//                    DownloadTaskManager.getInstance().insertDownload(downLoadTask);
//                    sendMessageEnergy(context, downLoadTask.getGameId());
//                    StatFactory.getInstance().sendGameDownload(context, downLoadTask.getGameId(),3+"",isDetial);
//                    DownloadFactory.get().addTask(new DownloadTask(downLoadTask.getDownloadUrl(), downLoadTask.getDownPath(), downLoadTask.getGameId(), downLoadTask.getTotalSize()));
//
//                    MobileCodeUtils.taskDownloadGameTag(context, downLoadTask.getGameId());
//                }
//            });
        } else {
            downLoadTask.setId(tableDb.getId());
            DownloadTaskManager.getInstance().updateDownloadTask(downLoadTask);
            DownloadFactory.get().addTask(new DownloadTask(downLoadTask.getDownloadUrl(), downLoadTask.getDownPath(), downLoadTask.getGameId(), downLoadTask.getTotalSize()));
        }

    }
}
